package org.hxzon.util.sort;

import java.util.Comparator;

public class QuickSelect {
    //private static int cutoff = 1;

    public static <T> void quickSelectMinK(T a[], int k, Comparator<T> comp) {
        quickSelectMinK(a, k, 0, a.length - 1, comp);
    }

    //QuickSelect 将第k小的元素放在 a[k-1]
    public static <T> void quickSelectMinK(T a[], int k, int left, int right, Comparator<T> comp) {
        if (left >= right) {
            return;
        }
        //取三数中值作为枢纽元，可以很大程度上避免最坏情况
        int vi = QuickSort.median3Index(a, left, right, (right + left) / 2, comp);
        //System.out.println("v:" + a[vi]);
        QuickSort.swap(a, left, vi);
        //
        int i = left + 1;
        int j = right;
        while (true) {
            while (comp.compare(a[j], a[left]) > 0) {
                j--;
            }
            while (comp.compare(a[i], a[left]) < 0) {
                i++;
            }
            if (i < j) {
                QuickSort.swap(a, i, j);
                i++;
                j--;
            } else {
                break;
            }
        }
        //重置枢纽元
        QuickSort.swap(a, left, i - 1);//vi=i-1
        //if k=vi or k=vi+1,is complete
        //
        if (k < i - 1) {//k<vi
            quickSelectMinK(a, k, left, i - 2, comp);//vi-1
        } else if (k > i) {//k>vi+1
            quickSelectMinK(a, k, i, right, comp);//vi+1
        }

    }

    //=====================
    public static <T> void quickSelectMinK_2(T a[], int k, Comparator<T> comp) {
        quickSelectMinK(a, k, 0, a.length - 1, comp);
    }

    //QuickSelect 将第k小的元素放在 a[k-1]
    public static <T> void quickSelectMinK_2(T a[], int k, int left, int right, Comparator<T> comp) {
        if (left >= right) {
            return;
        }
        //取三数中值作为枢纽元，可以很大程度上避免最坏情况
        int vi = QuickSort.median3Index(a, left, right, (right + left) / 2, comp);
        QuickSort.swap(a, vi, right);
        //
        int i = left - 1;
        int j = right;//begin form [right-1]
        while (true) {
            while (comp.compare(a[++i], a[right]) < 0) {
            }
            while (comp.compare(a[--j], a[right]) > 0) {
            }
            if (i < j) {
                QuickSort.swap(a, i, j);
            } else {
                break;
            }
        }
        //重置枢纽元
        QuickSort.swap(a, i, right);

        if (k <= i) {
            quickSelectMinK(a, k, left, i - 1, comp);
        } else if (k > i + 1) {
            quickSelectMinK(a, k, i + 1, right, comp);
        }
    }
}
